import React, { Component } from 'react';
import {connect} from "dva/index";
import { Icon, Button, Input, Form, message,Spin} from 'antd';
import {withPropsAPI} from "gg-editor";
import styles from './index.less';
import savebuttom from '@/assets/account/robotSetup/savebuttom.png';
import addImg from '@/assets/dialog/add1.png';
import delImg from '@/assets/dialog/del.png';
import moveImg from '@/assets/dialog/start/move.png';
const FormItem = Form.Item;


@connect(({ collectSlot, loading }) => ({
  collectSlot,
  loading: loading.effects['collectSlot/fetchSlot'],
}))
class DialogStart extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      addValue:"",
      questions:["发电机房定时接口你发个人", "鸡扣费我试了顾客聚聚哦喷淋管"],
      slots:[],
      questionIndex:-1,
      nodeId: props.nodeId,
      stage: props.stage,
      dialogId: props.dialogId,// 多轮对话id
      stageId: "",
      loading:true
    };
  }


  componentDidMount() {
    this.getInit();
    this.getDialogSlots();
  };

  getInit = () =>{
    const { dispatch ,dialogId,nodeId, stage} = this.props;
    console.log("dialogId :" + dialogId + ", nodeId :" + nodeId + ", stage :" + JSON.stringify(stage));
    dispatch({
      type: 'collectSlot/fetchSlot',
      payload: {
        stage: "start",
        dialogId: dialogId,
        nodeId: nodeId,
      },
      callback:(res)=>{
        console.log("开始模块初始值res :" + JSON.stringify(res));
        this.setState({
          stageId: res.dialogStage._id,
          questions: res.dialogStage.data.questions==undefined?[]:res.dialogStage.data.questions,
          loading:false
        })
      }
    });
  };

  getDialogSlots = ()=>{
    const { dialogId } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/getDialogSlots',
      payload: {
        dialogId: dialogId
      },
      callback:(res)=>{
        this.setState({
          slots: res,
        })
        console.log("词槽列表 :" + JSON.stringify(res));
      }
    });
  };

  addValue = () =>{
    const { questions,addValue } = this.state;
    switch (addValue.trim()){
      case "":
        message.info("相似问不能为空");
        break;
      default:
        questions.push(addValue);
        this.setState({
          questions: questions,
          addValue: "",
        })
    }
  };

  onChange = (e, type, index) =>{
    switch (type){
      case "a":
        this.setState({
          addValue: e.target.value,
        });
        break
      case "b":
        const { questions } = this.state;
        questions[index] = e.target.value;
        this.setState({
          questions: questions,
        });
        break
    }
  };

  changeQuestions =(q,i,type)=>{
    const { questions } = this.state;
    switch (type){
      case "del":
        questions.splice(i,1);
        this.setState({
          questions: questions,
        });
        break
      case "up":
        questions.splice(i,1);
        questions.unshift(q);
        this.setState({
          questions: questions,
        });
        break
    }
  };

  changeQuestionsIndex =(i)=>{
    this.setState({
      questionIndex: i,
    });
  };

  addSlots = (name,index) =>{
    const { addValue,questions } = this.state;
    if(index===-1){
      const newValue = addValue+"<" + name +">";
      this.setState({
        addValue: newValue
      });
    }else{
      const newValue = questions[index]+"<" + name +">";
      questions[index] = newValue;
      this.setState({
        questions: questions
      });
    }

    const resemblanceX = `resemblance${index}`;
    this.refs[resemblanceX].focus();
  };

  save = () =>{
    const { questions, stageId } = this.state;
    const { dispatch } = this.props;
    if(questions.length <= 0){
      message.info("请至少填写一条相似问");
    }else{
      dispatch({
        type: 'dialogStart/saveStage',
        payload: {
          _id: stageId,
          field: "data",
          data: {
            autoEnter: true,
            questions: questions
          },
        },
        callback:(res)=>{
          console.log("res :" + JSON.stringify(res));
          if(res.code === 0){
            message.info("保存成功");
          }else{
            message.info("保存失败");
          }
        }
      });
    }
  };

  render() {
    const { questions,slots,loading } = this.state;
    return(
      <div style={{width: '100%',margin:'15px 0px'}}>
        <p style={{color:'#71a3f1',fontSize:'21px'}}>自定义触发相似问</p>
        <div>
          <Input
            style={{ width: '89%' , lineheight: '35px'}}
            placeholder="请输入相似问题, 点击回车继续添加"
            className={styles.inputItem1}
            value={this.state.addValue}
            onChange={event=>{this.onChange(event,"a",-1)}}
            onPressEnter={this.addValue}
            onFocus={e=>this.changeQuestionsIndex(-1)}
            ref={`resemblance-1`}
          />
          <span>
            <img src={addImg} onClick={this.addValue} alt="" height={47}/>
          </span>
          <div>
            {
              slots.map((slotItem)=>{
                return (
                  <Button htmlType='button' size="small" style={{marginRight:10,marginTop:10}} onClick={() => this.addSlots(slotItem.slotName, -1)}>&lt;{slotItem.slotName}&gt;</Button>
                )
              })
            }
          </div>
        </div>

        {
          questions.map((q,i)=>{
            return(
              <div style={{width: '100%',margin:'15px 0px'}}>
                <Spin spinning={loading}>
                <div className={styles.item}>
                  <Input
                    style={{ width: '100%' }}
                    className={styles.inputItem}
                    value={q}
                    onChange={event=>{this.onChange(event,"b",i)}}
                    onFocus={e=>this.changeQuestionsIndex(i)}
                    ref={`resemblance${i}`}
                  />
                  <span className={styles.tool}>
                    <img src={moveImg} alt=""  onClick={() => this.changeQuestions(q,i,"up")} className={styles.toolImg} />
                    <img src={delImg} alt="" onClick={() => this.changeQuestions(q,i,"del")} className={styles.toolImg} />
                  </span>
                  <div>
                    {
                      this.state.questionIndex===i?
                      slots.map((slotItem)=>{
                        return (
                          <Button htmlType='button' size="small" style={{marginRight:10,marginTop:10}}  onClick={() => this.addSlots(slotItem.slotName, i)}>&lt;{slotItem.slotName}&gt;</Button>
                        )
                      }):null
                    }
                  </div>
                </div>
                </Spin>
              </div>
            )
          })
        }

        <div className={styles.flexcen}>
          {/*<Button type="primary" onClick={this.save}>保存</Button>*/}
          <img onClick={this.save} src={savebuttom} />
        </div>
      </div>
    )
  }
}

export default withPropsAPI(DialogStart);
